package com.yunxi.module.infra.service.logger.impl;

import com.yunxi.framework.common.util.object.BeanUtils;
import com.yunxi.module.infra.dto.logger.ApiErrorLogCreateReqDTO;
import com.yunxi.module.infra.enums.logger.ApiErrorLogProcessStatusEnum;
import com.yunxi.module.infra.mapper.logger.ApiErrorLogMapper;
import com.yunxi.module.infra.model.logger.ApiErrorLogDO;
import com.yunxi.module.infra.service.logger.ApiErrorLogService;
import groovy.util.logging.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * API 错误日志 Service 接口实现类
 * </p>
 *
 * @author lidy
 * @since 2024-05-17
 */
@Slf4j
@Validated
@Service
public class ApiErrorLogServiceImpl implements ApiErrorLogService {

    @Resource
    private ApiErrorLogMapper apiErrorLogMapper;

    /**
     * 创建 API 错误日志
     *
     * @param reqDTO API 错误日志
     */
    @Override
    public void createApiErrorLog(ApiErrorLogCreateReqDTO reqDTO) {
        ApiErrorLogDO apiErrorLogDO = BeanUtils.toBean(reqDTO, ApiErrorLogDO.class);
        apiErrorLogDO.setProcessStatus(ApiErrorLogProcessStatusEnum.INIT.getStatus());
        apiErrorLogMapper.insert(apiErrorLogDO);
    }


    /**
     * 清理 exceedDay 天前的错误日志
     *
     * @param exceedDay   超过多少天就进行清理
     * @param deleteLimit 清理的间隔条数
     * @return 结果
     */
    @Override
    @SuppressWarnings("DuplicatedCode")
    public Integer cleanErrorLog(Integer exceedDay, Integer deleteLimit) {
        int count = 0;
        LocalDateTime expireDate = LocalDateTime.now().minusDays(exceedDay);
        // 循环删除，直到没有满足条件的数据
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            int deleteCount = apiErrorLogMapper.deleteByCreateTimeLt(expireDate, deleteLimit);
            count += deleteCount;
            // 达到删除预期条数，说明到底了
            if (deleteCount < deleteLimit) {
                break;
            }
        }
        return count;
    }
}
